class Server {
  constructor() {
    // 初始化
    this.init()
    // this.other()
  }
  init() {
    // 引入功能模块
    this.os = require('os')
    this.http = require('http')
    this.fs = require('fs')
    this.url = require('url')
    this.querystring = require('querystring');
    // 创建服务器
    this.server = this.http.createServer()
    // 启动服务器
    this.start()
    // 相应请求
    this.request()
  }
  start() {
    // 启动服务器，监听端口
    this.server.listen(2333, () => {
      console.log('服务器已启动：http://127.0.0.1:2333/')
    })
  }
  request() {
    // 处理请求
    this.server.on('request', (request, response) => {
      //判断请求的方式
      console.log('request.method', request.method)
      // 处理跨域
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Headers", "Origin,No-Cache,X-Requested-With,If-Modified-Since,Pragma,Last-Modified,Cache-Control,Expires,Content-Type,Access-Control-Allow-Credentials");
      response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
      response.setHeader("X-Powered-By", ' 3.2.1');
      response.setHeader("Content-Type", "text/plain; charset=utf-8");
      // 获取URL参数
      // 核心模块法
      console.log(this.url.parse(request.url, true).pathname)
      console.log(this.url.parse(request.url, true).query)
      // 正则匹配法
      if (request.url.match(/submit/i)) { // post 请求请求提交数据
        this.subItem(request, response)
      } else if (request.url.match(/about/i)) { // 服务端模版引擎渲染
        this.renderPage(response)
      } else { // get请求
        this.getList(response)
      }
      // this.readTemp('index.html', response)
    })
  }
  getList(res) {
    this.fs.readFile('source/listData.json', (err, data) => {
      res.end(data.toString())
    })
  }
  subItem(req, res) {
    let data = ''
    req.on('data', (chunk) => {
      data += chunk
    })
    req.on('end', () => {
      if (data) {
        this.addItem(JSON.parse(data))
      }
      res.end('success')
    })
  }
  addItem(item) {
    this.fs.readFile('./source/listData.json', (err, data) => {
      if (err) console.log(err)
      let list = JSON.parse(data.toString())
      list.push(item)
      this.fs.writeFile('./source/listData.json', JSON.stringify(list), (err) => {
        if (err) console.error(err)
        console.log('更新数据成功')
      })
    })
  }
  renderPage(res) {
    res.setHeader("Content-Type", "text/html; charset=utf-8");
    let template = require('art-template');
    let html = template(__dirname + '/source/art.html', {
      user: {
        name: 'hello browniu'
      },
      target: ['xixi', 'haha', 'gugu', 'gaga', 'jiji']
    });
    res.end(html)
  }
  readTemp(e, response) {
    this.fs.readFile('source/' + e, (err, data) => {
      response.end(data.toString())
    })
  }
  other() {}
}

let server = new Server()
server.other()